package com.jzo2o.foundations.service.impl;

import co.elastic.clients.elasticsearch._types.SortOptions;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.es.core.ElasticSearchTemplate;
import com.jzo2o.es.utils.SearchResponseUtils;
import com.jzo2o.foundations.model.domain.ServeAggregation;
import com.jzo2o.foundations.model.dto.response.ServeSimpleResDTO;
import com.jzo2o.foundations.service.ServeAggregationService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ServeAggregationServiceImpl implements ServeAggregationService {
    @Resource
    private ElasticSearchTemplate elasticSearchTemplate;


    /**
     * 查询服务列表
     *
     * @param cityCode    城市编码
     * @param serveTypeId 服务类型id
     * @param keyword     关键词
     * @return 服务列表
     */
    @Override
    public List<ServeSimpleResDTO> findServeList(String cityCode, Long serveTypeId, String keyword) {
        // 构建查询条件
        SearchRequest.Builder builder = new SearchRequest.Builder();
        builder.query(query -> {
            query.bool(bool -> {
                // 根据区域码精确匹配
                bool.must(must ->
                    must.term(term ->
                         term.field("city_code").value(cityCode)
                    )
                );
                if(!ObjectUtils.isNull(serveTypeId)) {
                    // 根据服务类型精确匹配
                    bool.must(must ->
                            must.term(term ->
                                    term.field("serve_type_id").value(serveTypeId)
                            )
                    );
                }
                // 根据关键字多字段匹配
                if(!ObjectUtils.isEmpty(keyword)) {
                    bool.must(must ->
                            must.multiMatch(match ->
                                    match.fields("serve_item_name", "serve_type_name")
                                         .query(keyword)
                            )
                    );
                }
                return bool;
            });
            return query;
        });

        // 构建排序条件
        List<SortOptions> sortOptionsList = new ArrayList<>();
        builder.sort(SortOptions.of(sortOptions ->
                sortOptions.field(field ->
                        field.field("serve_item_sort_num")
                             .order(SortOrder.Asc)
                )
        ));
        // 指定索引库
        builder.index("serve_aggregation");
        // 构建SearchRequest
        SearchRequest searchRequest = builder.build();

        // 请求ES获取并解析数据
        SearchResponse<ServeAggregation> searchResult
                = elasticSearchTemplate.opsForDoc().search(searchRequest, ServeAggregation.class);
        if(SearchResponseUtils.isSuccess(searchResult)) {
            // 解析数据
            List<ServeAggregation> collect = searchResult.hits().hits().stream()
                    .map(Hit::source).collect(Collectors.toList());
            // 数据封装并返回
            List<ServeSimpleResDTO> copyToList = BeanUtils.copyToList(collect, ServeSimpleResDTO.class);
            return copyToList;
        }

        // 查询不到结果返回空集合
        return Collections.emptyList();
    }
}
